package com.mtw.bbs.fileAdmin.controller;

import com.mtw.bbs.common.core.vo.Result;
import com.mtw.bbs.fileAdmin.exception.FileBusException;
import com.mtw.bbs.fileAdmin.pojo.vo.FileVo;
import com.mtw.bbs.fileAdmin.service.FileService;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;



@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("provide/file")
public class FileProvider {


    private final FileService fileService;



    @GetMapping(value = "url")
    @ApiOperation(value = "获取文件url")
    public Result<FileVo> getFileUrlById(@RequestParam("id") String id) {

        try {
            return Result.success(fileService.getFileUrl(id));
        }catch (FileBusException e){
            log.error("获取文件url失败，id：{}。",id,e);
            return Result.fail(e.getMessage());
        }
    }


    @ApiOperation(value = "批量获取获取文件url")
    @PostMapping(value = "/urls")
    public Result getFileUrlByIdArray(@RequestBody String[] ids) {

        try {
            List<FileVo> list = new ArrayList<>(ids.length);
            for (String id : ids) {
                FileVo fileUrl = fileService.getFileUrl(id);
                if (fileUrl != null){
                    list.add(fileUrl);
                }
            }
            return Result.success(list);
        }catch (Exception e){
            log.error("获取文件url失败，ids：{}。",ids,e);
            return Result.fail(e.getMessage());
        }
    }
}
